import { Context, Next } from 'koa';
import { Controller, get, post } from 'koa-router-decorators-plus';
import { getManager } from 'typeorm';
import { Detail } from '../mysql/entity/detail';
import { User } from '../mysql/entity/user';
import R from '../utils/response';

@Controller('/user')
export default class user {
    @post('/add')
    async getIndex(ctx: Context, next: Next) {
        const userSchema = getManager().getRepository(User)
        userSchema.findOne
        const { name, password, email } = ctx.request.body as {
            name: string,
            password: string,
            email: string
        }
        //在正常开发中密码建议加密保存
        const newUser = new User()
        newUser.name = name
        newUser.email = email
        newUser.password = password
        // 保存到数据库
        const user = await userSchema.save(newUser);
        if (user) {
            ctx.body = {
                user
            }
        } else {
            ctx.body = {
                msg: '出错了'
            }
        }
    }
    @get('/findalluser')
    async getString(ctx: Context, next: Next) {
        const detailSchema = getManager().getRepository(Detail)
        const detailist = await detailSchema.find({
            relations: ['user'], where: {
                age: 12
            }
        })
        var res = R.successResult({ detailist })
        return res
    }

    @get()
    async getByBuilder(ctx: Context, next: Next) {
        const detailist = await getManager().query(`
            SELECT user.id, user.name, detail.age, detail.address FROM user LEFT JOIN detail ON user.id = detail.userId
        `)
        var res = R.successResult({ detailist })
        return res
    }
}
